import 'dart:convert';
import 'dart:io';

import 'package:city_pickers/city_pickers.dart';
import 'package:common_utils/common_utils.dart';
import 'package:fluro/fluro.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_picker/picker.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';
import 'package:image_picker/image_picker.dart';
import 'package:taonile/utils/oss_upload_util.dart';

import '../config/config.dart';
import '../entity/user_info_entity.dart';
import '../http/api.dart';
import '../provider/userinfo_provider.dart';
import '../routers/routers.dart';

class MineInfo extends StatefulWidget {
  const MineInfo({Key? key}) : super(key: key);

  @override
  State<MineInfo> createState() => _MineInfoState();
}

class _MineInfoState extends State<MineInfo> {
  late UserInfoEntity infoEntity;
  String gender = '未设置';
  List<String> genders = ['男', '女'];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  chooseImage() async {
    final ImagePicker _picker = ImagePicker();
    final XFile? image = await _picker.pickImage(source: ImageSource.gallery);
    String? imgPah = image?.path;
    if (imgPah != null) {
      LogUtil.v(imgPah, tag: '选择的图片路径=');
      EasyLoading.show(status: 'loading...');
      String result = await UploadOss.upload(File(imgPah), fileType: UploadOss.getFileType(imgPah));
      upUserInfo(result);
      EasyLoading.dismiss();
    }
  }

  upUserInfo(String url) async {
    dynamic result = await Api.upUserinfo({'avatar': url});
    var jsonResult = jsonDecode(jsonEncode(result));
    if (jsonResult['code'] == 1) {
      dynamic users = await Api.getUserinfo();
      Map<String, dynamic> resultUsers = Map.from(users);
      UserInfoEntity infoEntity = UserInfoEntity.fromJson(resultUsers);
      Provider.of<UserInfoProvider>(context, listen: false).changeUserinfo(infoEntity);
      EasyLoading.showToast("修改成功");
    }
  }

  Widget getListItem(IconData icon, String title, String subTitle, Function() onTap) {
    return ListTile(
      onTap: onTap,
      leading: Icon(icon, size: 43.w),
      title: Text(title, style: TextStyle(fontSize: 25.w)),
      horizontalTitleGap: 0,
      dense: true,
      iconColor: Config.colorText1,
      textColor: Config.colorText1,
      trailing: SizedBox(
        width: 360.w,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.end,
          children: [
            Text(subTitle, style: TextStyle(fontSize: 23.w, color: Config.colorText3)),
            Padding(padding: EdgeInsets.all(10.w)),
            Icon(Icons.arrow_forward_ios, size: 20.w),
          ],
        ),
      ),
      contentPadding: EdgeInsets.symmetric(vertical: 9.w, horizontal: 0),
    );
  }

  ///
  /// 返回头像item
  ///
  Widget getListItemAvatar(IconData icon, String title, Function() onTap) {
    return ListTile(
      onTap: onTap,
      leading: Icon(icon, size: 43.w),
      title: Text(title, style: TextStyle(fontSize: 25.w)),
      horizontalTitleGap: 0,
      dense: true,
      iconColor: Config.colorText1,
      textColor: Config.colorText1,
      trailing: SizedBox(
        width: 300.w,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.end,
          children: [
            Container(
                width: 95.w,
                height: 95.w,
                color: Colors.transparent,
                padding: EdgeInsets.all(3.w),
                child: CircleAvatar(
                  backgroundImage: getHeadImage(),
                )),
            Padding(padding: EdgeInsets.all(10.w)),
            Icon(Icons.arrow_forward_ios, size: 20.w),
          ],
        ),
      ),
      contentPadding: EdgeInsets.symmetric(vertical: 9.w, horizontal: 0),
    );
  }

  ///
  /// 判断头像有木有，没有就用本地的占位
  ///
  ImageProvider getHeadImage() {
    if (infoEntity.code == 1 && infoEntity.data.avatar.length > 1) {
      return NetworkImage(infoEntity.data.avatar);
    } else {
      return const AssetImage('assets/images/icon_default_head.jpg');
    }
  }

  getGender(String status) {
    if (status == '1') {
      return '男';
    } else if (status == '2') {
      return '女';
    } else {
      return '未设置';
    }
  }

  chooseGender(BuildContext context) async {
    Picker(
        adapter: PickerDataAdapter(pickerData: genders, isArray: false),
        height: 300.w,
        headerDecoration: BoxDecoration(
          color: Config.colorWhite,
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(20.w),
            topRight: Radius.circular(20.w),
          ),
        ),
        itemExtent: 70.w,
        confirmText: '确定',
        cancelText: '取消',
        columnPadding: EdgeInsets.all(15.w),
        onConfirm: (picker, list) {
          // LogUtil.v(SingletonManager.instance.orderCancelReason[list[0]]);
          postGender(list[0]);
        }).showModal(context, backgroundColor: Colors.transparent);
  }

  postGender(int index) async {
    String gender = '0';
    if (index == 0) {
      gender = '1';
    } else {
      gender = '2';
    }
    dynamic result = await Api.upUserinfo({'gender': gender});
    var jsonResult = jsonDecode(jsonEncode(result));
    if (jsonResult['code'] == 1) {
      EasyLoading.showToast("提交成功");
      infoEntity.data.gender = gender;
      Provider.of<UserInfoProvider>(context, listen: false).changeUserinfo(infoEntity);
    }
  }

  @override
  Widget build(BuildContext context) {
    infoEntity = Provider.of<UserInfoProvider>(context).userInfo;
    setState(() {
      gender = getGender(infoEntity.data.gender);
    });
    return Scaffold(
      backgroundColor: Config.colorBg2,
      appBar: AppBar(
        title: const Text('个人设置'),
        centerTitle: true,
      ),
      body: Container(
        //中间列表区
        width: double.infinity,
        height: 360.w,
        padding: EdgeInsets.symmetric(vertical: 0, horizontal: 0.w),
        margin: EdgeInsets.symmetric(vertical: 30.w, horizontal: 30.w),
        decoration: BoxDecoration(
          color: (Config.colorWhite),
          borderRadius: BorderRadius.circular(12.w),
        ),
        child: ListView(
          physics: const NeverScrollableScrollPhysics(),
          padding: EdgeInsets.symmetric(vertical: 6.w, horizontal: 30.w),
          children: [
            getListItemAvatar(Icons.person, "头像", () {
              chooseImage();
            }),
            const Divider(
              height: 0.5,
              color: Config.colorDivider,
            ),
            // getListItem(Icons.account_circle_outlined, "账号", infoEntity.data.name, () {}),
            // const Divider(
            //   height: 0.5,
            //   color: Config.colorDivider,
            // ),
            // getListItem(Icons.person_add, "昵称", '', () {
            //   Routes.navigateTo(context, Routes.mineChangeNickname);
            // }),
            getListItem(Icons.transgender, "性别", gender, () {
              chooseGender(context);
            }),
            const Divider(
              height: 0.5,
              color: Config.colorDivider,
            ),
            getListItem(Icons.add_location_alt, "收货地址", '', () {
              Routes.navigateTo(context, Routes.mineAddressManager);
            }),
          ],
        ),
      ),
    );
  }
}
